import { trigger, animate, transition, style, state, Component, ElementRef, AfterViewInit, DoCheck, OnDestroy, Input, Output, IterableDiffers } from '@angular/core';
import { Message } from "../messageBox/confirmMessage";

@Component({
    selector: 'growl',
    styleUrls: [
        './common-components.scss'
    ],
    template: `
       <div class="growl-container">
            <div  [@flyInOut] *ngFor="let msg of value" class="item" [ngClass]="{'info':msg.severity == 'info','warn':msg.severity == 'warn','error':msg.severity == 'error','success':msg.severity == 'success'}">
                <div>
                    <p>{{msg.title}}</p>
                </div>
                <span (click)="remove(msg,msgel)" class="icon"><i class="iconfont icon-clear"></i></span>
            </div>
        </div>
    `,
    animations: [
        trigger('flyInOut', [
            state('in', style({ height: "50px", opacity: 100 })),
            transition('void => *', [
                style({ height: '0px', opacity: 0 }),
                animate(300)
            ]),
            transition('* => void', [
                animate(1000, style({ opacity: 0 }))
            ])
        ])
    ],
    providers: []
})




export class Growl {

    @Input() sticky: boolean = false;

    @Input() life: number = 1500;

    @Input() value: Message[];



    container: any;
    timeout

    constructor(private el: ElementRef) {


    }

    ngDoCheck() {
        this.removeAll();
    }

    ngAfterViewInit() {
        // setTimeout(() => {
        //     this.value = [];
        // }, 5000);
    }



    remove(msg: Message, msgel: any) {
        setTimeout(() => {
            this.value.splice(this.findMessageIndex(msg), 1);
        }, 250);
    }

    removeAll() {
        if (this.value && this.value.length) {
            setTimeout(() => {
                this.value.splice(0, this.value.length);
            }, 2250);
        }
    }

    findMessageIndex(msg: Message) {
        let index: number = -1;

        if (this.value && this.value.length) {
            for (let i = 0; i < this.value.length; i++) {
                if (this.value[i] == msg) {
                    index = i;
                    break;
                }
            }
        }

        return index;
    }

    ngOnDestroy() {
        if (!this.sticky) {
            clearTimeout(this.timeout);
        }
    }

}